package com.miya.demo.common.util;

import cn.hutool.json.JSONUtil;
import com.miya.demo.model.dto.wechat.TemplateMsgDTO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 我们聊天模板工具类
 *
 * @author CaiXiaowei
 * @date 2022/08/31
 */
@Slf4j
public class WeChatTemplateUtils {

    /**
     * 封装微信公众号消息模板参数
     * @param templateMsgDTO
     * @return
     */
    @SneakyThrows
    public static String getSendPublicNoTemplateContentParams(TemplateMsgDTO templateMsgDTO)  {
        Map mapReq = new HashMap(8);
        mapReq.put("touser",templateMsgDTO.getToUser());
        mapReq.put("template_id",templateMsgDTO.getTemplateId());
        String url = templateMsgDTO.getUrl();
        if (StringUtils.isNotBlank(url)) {
            mapReq.put("url",url);
        }
        TemplateMsgDTO.Miniprogram miniprogram = templateMsgDTO.getMiniprogram();
        if (Objects.nonNull(miniprogram)) {
            Map map =new HashMap(8);
            map.put("pagepath",miniprogram.getPagepath());
            map.put("appid",miniprogram.getAppId());
            mapReq.put("miniprogram",map);
        }
        mapReq.put("data", JSONUtil.parseObj(templateMsgDTO.getData()));
        return JSONUtil.toJsonStr(mapReq);
    }

    /**
     * 封装微信小程序消息模板参数
     * @param templateMsgDTO
     * @return
     */
    @SneakyThrows
    public static String getSendMiniAppTemplateContentParams(TemplateMsgDTO templateMsgDTO){
        Map mapReq = new HashMap(8);
        mapReq.put("touser",templateMsgDTO.getToUser());
        mapReq.put("template_id",templateMsgDTO.getTemplateId());
        mapReq.put("miniprogram_state",templateMsgDTO.getMiniprogramState());
        mapReq.put("lang",templateMsgDTO.getLang());
        String url = templateMsgDTO.getUrl();
        if (StringUtils.isNotBlank(url)) {
            mapReq.put("page",url);
        }
        mapReq.put("data", JSONUtil.parseObj(templateMsgDTO.getData()));
        String templateStr = JSONUtil.toJsonStr(mapReq);
        log.info("组装模板消息:{}", templateStr);
        return templateStr;
    }

}
